package com.nuanshui.heatedloan.credit.service;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.nuanshui.framework.consts.TransactionManagerType;
import com.nuanshui.framework.lang.DateUtil;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.security.DESC;
import com.nuanshui.heatedloan.baseservice.service.CommonServiceImpl;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.constant.RabbitMqQueue;
import com.nuanshui.heatedloan.constant.ServiceConstant;
import com.nuanshui.heatedloan.credit.constant.BorrowType;
import com.nuanshui.heatedloan.credit.constant.OrderType;
import com.nuanshui.heatedloan.credit.constant.PersonPageStatusConstant;
import com.nuanshui.heatedloan.credit.constant.ReturnClientStatus;
import com.nuanshui.heatedloan.credit.facade.*;
import com.nuanshui.heatedloan.credit.facade.third.party.*;
import com.nuanshui.heatedloan.credit.form.CustomerCreditResultForm;
import com.nuanshui.heatedloan.credit.model.record.WhiteListResultRecord;
import com.nuanshui.heatedloan.credit.mongodb.WhiteListResultRecordRepository;
import com.nuanshui.heatedloan.credit.msg.CreditPushConstant;
import com.nuanshui.heatedloan.credit.msg.CreditPushMsgService;
import com.nuanshui.heatedloan.credit.request.CalculationLimitRequest;
import com.nuanshui.heatedloan.credit.request.IdCardInfo;
import com.nuanshui.heatedloan.credit.request.IsWhiteRequest;
import com.nuanshui.heatedloan.credit.response.CalculationLimitResponse;
import com.nuanshui.heatedloan.credit.response.ClientResponse;
import com.nuanshui.heatedloan.credit.response.IsWhiteResponse;
import com.nuanshui.heatedloan.credit.response.PersonPageStatusResponse;
import com.nuanshui.heatedloan.credit.vo.*;
import com.nuanshui.heatedloan.middleware.rabbitmq.RabbitmqMessageSender;
import com.nuanshui.heatedloan.msgcenter.integration.CreditPushMsgBody;
import com.nuanshui.heatedloan.userinfo.model.SimpleUserInfo;
import com.nuanshui.heatedloan.userinfo.tool.UserTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import com.nuanshui.heatedloan.service.services.CommonTool;

/**
 * Created by wangxw on 2017/6/26.
 */
@Service(ServiceConstant.EXECUTECUSTOMAUTHSERVICE)
@Transactional(readOnly=true,value= TransactionManagerType.CREDIT_TRANSACTION_MANAGER)
public class ExecuteCustomAuthServiceImpl extends CommonServiceImpl implements ExecuteCustomAuthService {

      private  static  final Logger logger= LoggerFactory.getLogger(CustomerBankCardInfoServiceImpl.class);

      @Autowired
      private CustomerBankCardInfoService customerBankCardInfoService;

      @Autowired
      private CustomerPeopleRelationshipService customerPeopleRelationshipService;

      @Autowired
      private CustomerCompanyInfoService customerCompanyInfoService;

      @Autowired
      private SesameCreditAuthService sesameCreditAuthService;

      @Autowired
      private PhoneNumAuthService phoneNumAuthService;

      @Autowired
      private JingDongAuthService jingDongAuthService;

      @Autowired
      private CreditCardAuthService creditCardAuthService;

      @Autowired
      private CustomerIdCardInfoService customerIdCardInfoService;

      @Autowired
      private CustomerCreditResultService customerCreditResultService;

      @Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
      private UserTool userTool;

    @Autowired
    private RabbitmqMessageSender rabbitmqMessageSender;


    //消息和推送
    @Autowired
    private CreditPushMsgService creditPushMsgService;

    @Autowired
    private RiskManagerInteractionService riskManagerInteractionService;
    @Autowired
    private PayOrderInfoService payOrderInfoService;

    @Autowired
    private WhiteListResultRecordRepository whiteListResultRecordRepository;

    @Override
    public Map<String, Object> getCustomAuthStatus(String userId,int type) {
        Map<String,Object> map=new HashMap<String,Object>();
        if(1==type){
            this.getNeedAuthStatus(userId,map);
        }else{
            this.getOptionalAuth(userId,map);
        }
        return map;
    }

    private Map<String,Object>  getNeedAuthStatus(String userId, Map<String,Object> map){
        //银行卡基本信息
        List<CustomerBankCardInfoVO> customerBankCardInfoVOs=customerBankCardInfoService.loadCustomerBankCardInfoVOByUserId(userId);
        //银行卡基本信息  modifyby:zss 用户银行有多个，此方法要修改
        if(customerBankCardInfoVOs!=null&&customerBankCardInfoVOs.size()>0){
            map.put("customerBankCard",1);
        }else {
            map.put("customerBankCard", 0);
        }
        //客户身份信息
        CustomerIdCardInfoVO customerIdCardInfoVO=customerIdCardInfoService.loadByUserId(userId);
        this.getCustomAuthStatusMap(customerIdCardInfoVO,"customerIdCard",map);
        //客户人员关系
        List<CustomerPeopleRelationshipVO> customerPeopleRelationshipVO=customerPeopleRelationshipService.loadcustomerPeopleRelationshipVOByCusId(userId);
        this.getCustomAuthStatusMap(customerPeopleRelationshipVO,"customerPeopleRelationship",map);
        //工作信息
        CustomerCompanyInfoVO customerCompanyInfoVO=customerCompanyInfoService.loadVOByUserId(userId);
        this.getCustomAuthStatusMap(customerCompanyInfoVO,"customerCompanyInfo",map);
        //芝麻认证信息
        CustomerSesameCreditInfoVO customerSesameCreditInfoVO=sesameCreditAuthService.loadVOByUserId(userId);
        if(customerSesameCreditInfoVO==null){
            map.put("customerSesameCreditInfo",0);
        }else if(customerSesameCreditInfoVO!=null){
           if("2".equals(customerSesameCreditInfoVO.getAuthFlag())){
               map.put("customerSesameCreditInfo",2);
           }else{
               map.put("customerSesameCreditInfo",1);
           }
        }
        return map;
    }


    private Map<String,Object>  getOptionalAuth(String userId, Map<String,Object> map){
        //手机认证信息
        CustomerPhoneInfoVO customerPhoneInfoVO=phoneNumAuthService.loadVOByUserId(userId);
        this.getCustomAuthStatusMap(customerPhoneInfoVO,"customerPhoneInfo",map);
        //京东认证信息
        CustomerJingDongInfoVO customerJingDongInfoVO=jingDongAuthService.loadVOByUserId(userId);
        this.getCustomAuthStatusMap(customerJingDongInfoVO,"customerJingDongInfo",map);
         //信用卡认证数据
        CustomerCreditCardInfoVO customerCreditCardInfoVO=creditCardAuthService.loadVOByUserId(userId);
        this.getCustomAuthStatusMap(customerCreditCardInfoVO,"customerCreditCardInfo",map);
        return map;
    }


    private void getCustomAuthStatusMap(Object object,String key,Map<String,Object> map){
        if(object!=null){
            map.put(key,1);
        }else{
            map.put(key,0);
        }
    }
    @Transactional(readOnly=false,value= TransactionManagerType.CREDIT_TRANSACTION_MANAGER)
    public void calculationLimit(String userId){
        CalculationLimitRequest calculationLimitRequest=new CalculationLimitRequest();
        IdCardInfo idCardInfo=new IdCardInfo();
        SimpleUserInfo simpleUserInfo=userTool.getSimpleUserInfo(userId);
        idCardInfo.setPhoneNum(simpleUserInfo.getPhone());
        calculationLimitRequest.setIdCardInfo(idCardInfo);
        logger.info("=============开始封装计算额度参数===========================");
        calculationLimitRequest.setCustomerId(userId);
        CalculationLimitResponse calculationLimitResponse=
                riskManagerInteractionService.calculationLimit(calculationLimitRequest);
        if(calculationLimitResponse==null){
            return ;
        }
        logger.info("=============调用风控接口完成===========================");
        CustomerCreditResultForm customerCreditResult=new CustomerCreditResultForm();
        customerCreditResult.setUserId(userId);
        customerCreditResult.setStatus(1);
        customerCreditResultService.save(customerCreditResult);
    }

    public void  sendMqCallBackCalculationLimit(CalculationLimitResponse calculationLimitResponse){
        rabbitmqMessageSender.send(RabbitMqQueue.RABBIT_MQ_CALL_CALCULATION_LIMIT,calculationLimitResponse,true);
    }
    @Transactional(readOnly=false,value= TransactionManagerType.CREDIT_TRANSACTION_MANAGER)
    public void callBackCalculationLimit(CalculationLimitResponse calculationLimitResponse){
        riskManagerInteractionService.callBackCalculationLimit(calculationLimitResponse);
        logger.info("=============风控计算额度返回数据=====================");
        CustomerCreditResultForm customerCreditResult=new CustomerCreditResultForm();
        customerCreditResult.setUserId(calculationLimitResponse.getCustomerId());
        if(SysStringUtils.isNotEmpty(calculationLimitResponse.getInstallmentAmt())){
            customerCreditResult.setInstallmentAmt(Integer.parseInt(calculationLimitResponse.getInstallmentAmt()));  //分期
        }
        if(SysStringUtils.isNotEmpty(calculationLimitResponse.getSingleAmt())){
            customerCreditResult.setSingleAmt(Integer.parseInt(calculationLimitResponse.getSingleAmt()));   //单期
        }
        if(SysStringUtils.isNotEmpty(calculationLimitResponse.getTotalAmt())){
            customerCreditResult.setTotalAmt(Integer.parseInt(calculationLimitResponse.getTotalAmt()));  //总金额
        }
        if(SysStringUtils.isNotEmpty(calculationLimitResponse.getIrate())){
            customerCreditResult.setInstallmentRate(Integer.parseInt(calculationLimitResponse.getIrate()));  //分期利率
        }
        if(SysStringUtils.isNotEmpty(calculationLimitResponse.getSrate())){
            customerCreditResult.setSingleRate(Integer.parseInt(calculationLimitResponse.getSrate()));       //单期利率
        }
        customerCreditResult.setCalculateSuccessTime(DateUtil.getDateByPattern(DateUtil.getToday(),"yyyy-MM-dd HH:mm:ss"));
        customerCreditResult.setStatus(2);
        logger.info("=============风控计算额度返回数据=====================");
        //判断数据是否存在，存在先跟新status为0
        CustomerCreditResultVO customerCreditResultVO=customerCreditResultService.loadVOByUserId(calculationLimitResponse.getCustomerId());
        logger.info("==========="+ JSON.toJSONString(customerCreditResultVO));
        if(customerCreditResultVO!=null){
            customerCreditResultService.updateByUserId(customerCreditResult);
        }else{
            customerCreditResultService.save(customerCreditResult);
        }
        logger.info("=============开始发送推送===========================");
        this.sendPushAndMsg(calculationLimitResponse.getCustomerId(),calculationLimitResponse);
        logger.info("=============发送推送结束==================");
    }

    private void sendPushAndMsg(String userId,CalculationLimitResponse calculationLimitResponse){
        CreditPushMsgBody creditPushMsgBody =new CreditPushMsgBody();
        creditPushMsgBody.addDstUserId(userId);
        logger.info("=============推送的客户id"+userId+"======================");
        creditPushMsgBody.setAmount(Integer.parseInt(calculationLimitResponse.getTotalAmt()));
        //&&calculationLimitResponse.getInstallmentAmt()==0
        //暂时屏蔽分期贷逻辑
        if("0".equals(calculationLimitResponse.getSingleAmt())){
            creditPushMsgBody.setType(CreditPushConstant.NOT_PASS_AUTH_TYPE);
            creditPushMsgBody.setAmount(Integer.parseInt(calculationLimitResponse.getSingleAmt()));
        }
        //发送成功app
        else{
            creditPushMsgBody.setType(CreditPushConstant.PASS_AUTH_TYPE);
            creditPushMsgBody.setAmount(Integer.parseInt(calculationLimitResponse.getSingleAmt()));
        }
        creditPushMsgService.dealPush(creditPushMsgBody);
    }


    @Override
    public PersonPageStatusResponse getPersonPageStatus(String userId) {
        PersonPageStatusResponse personPageStatusResponse=new PersonPageStatusResponse();
        CustomerCreditResultVO customerCreditResultVO=customerCreditResultService.loadVOByUserId(userId);
        if(customerCreditResultVO==null){
            personPageStatusResponse.setStatus(PersonPageStatusConstant.NOCALCULATIONLIMIT);
        }else if(customerCreditResultVO!=null&&customerCreditResultVO.getStatus()==1){
            personPageStatusResponse.setStatus(PersonPageStatusConstant.CALCULATIONLIMITING);
        }else{
            personPageStatusResponse.setStatus(PersonPageStatusConstant.CALCULATIONLIMITED);
            personPageStatusResponse.setTotalAmt(customerCreditResultVO.getTotalAmt());
            List<Integer> status=new ArrayList<Integer>();
            status.add(OrderType.REIMBURSEMENT);
            status.add(OrderType.LATEPAYMENT);
            status.add(OrderType.OVERDUEPAYMENT);
            status.add(OrderType.NOREIMBURSEMENT);
            List<Integer> types=new ArrayList<Integer>();
            types.add(BorrowType.SINGLELOAN);
            types.add(BorrowType.LIGHTLOAN);
            types.add(BorrowType.INSTALLMENT);
            int count=payOrderInfoService.loadUserLoanAccountByStatusAndType(userId,status,types);
            personPageStatusResponse.setLoanCounts(count);
        }
        return personPageStatusResponse;
    }

    public ClientResponse isWhiteList(String phone,String userId){
        WhiteListResultRecord whiteListResultRecord=new WhiteListResultRecord();
        whiteListResultRecord.setPhone(DESC.decrypt3DES(phone));
        whiteListResultRecord.setUserId(userId);
        ClientResponse clientResponse = new ClientResponse();
        IsWhiteRequest isWhiteRequest=new IsWhiteRequest();
        isWhiteRequest.setPhoneNum(DESC.decrypt3DES(phone));
        IsWhiteResponse  isWhiteResponse=riskManagerInteractionService.isWhiteList(isWhiteRequest);
        //非白名单
        if(isWhiteResponse!=null){
            if("2".equals(isWhiteResponse.getResultCode())){
                clientResponse.setResultCode(ReturnClientStatus.FAIL);
                whiteListResultRecord.setResultCode(ReturnClientStatus.FAIL);
            }else{
                clientResponse.setResultCode(ReturnClientStatus.SUCCESS);
                whiteListResultRecord.setResultCode(ReturnClientStatus.SUCCESS);
            }
        }else{
            clientResponse.setResultCode(ReturnClientStatus.FAIL);
            whiteListResultRecord.setResultCode(ReturnClientStatus.FAIL);
        }
        rabbitmqMessageSender.send(RabbitMqQueue.RABBIT_MQ_SAVE_WHITE_LIST,whiteListResultRecord,true);
        return clientResponse;
    }
}
